package com.qst.controller;

import com.qst.pojo.entity.SystemSettings;
import com.qst.repository.SystemSettingsRepository;
import com.qst.service.EmailService;
import com.qst.service.NotificationService;
import com.qst.util.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * 系统设置控制器
 */
@RestController
@RequestMapping("/api/settings")
public class SettingsController {

    private static final Logger logger = LoggerFactory.getLogger(SettingsController.class);

    @Autowired
    private SystemSettingsRepository settingsRepository;

    @Autowired
    private EmailService emailService;

    @Autowired
    private NotificationService notificationService;

    /**
     * 获取系统配置
     */
    @GetMapping("/system")
    public Result<Map<String, Object>> getSystemSettings() {
        try {
            Map<String, Object> settings = new HashMap<>();
            
            // 从数据库获取配置，如果不存在则返回默认值
            settings.put("systemName", getSettingValue("system.name", "资源回收管理平台"));
            settings.put("version", getSettingValue("system.version", "1.0.0"));
            settings.put("description", getSettingValue("system.description", "智能资源回收管理平台，提供高效的回收物资管理服务"));
            settings.put("maintenanceMode", Boolean.parseBoolean(getSettingValue("system.maintenanceMode", "false")));
            settings.put("allowRegistration", Boolean.parseBoolean(getSettingValue("system.allowRegistration", "true")));
            
            return Result.success(settings);
        } catch (Exception e) {
            logger.error("获取系统配置失败", e);
            return Result.error("获取系统配置失败");
        }
    }

    /**
     * 更新系统配置
     */
    @PutMapping("/system")
    public Result<String> updateSystemSettings(@RequestBody Map<String, Object> settings) {
        try {
            // 检查维护模式是否改变
            boolean maintenanceModeChanged = false;
            boolean newMaintenanceMode = false;
            if (settings.containsKey("maintenanceMode")) {
                // 获取旧的维护模式状态
                Optional<SystemSettings> oldSetting = settingsRepository.findBySettingKey("system.maintenanceMode");
                boolean oldMaintenanceMode = oldSetting.map(s -> Boolean.parseBoolean(s.getSettingValue())).orElse(false);
                newMaintenanceMode = Boolean.parseBoolean(settings.get("maintenanceMode").toString());
                
                // 检查是否改变
                if (oldMaintenanceMode != newMaintenanceMode) {
                    maintenanceModeChanged = true;
                }
            }
            
            // 保存各个配置项到数据库
            if (settings.containsKey("systemName")) {
                saveSetting("system.name", settings.get("systemName").toString(), "system", "系统名称");
            }
            if (settings.containsKey("version")) {
                saveSetting("system.version", settings.get("version").toString(), "system", "系统版本");
            }
            if (settings.containsKey("description")) {
                saveSetting("system.description", settings.get("description").toString(), "system", "系统描述");
            }
            if (settings.containsKey("maintenanceMode")) {
                saveSetting("system.maintenanceMode", settings.get("maintenanceMode").toString(), "system", "维护模式");
            }
            if (settings.containsKey("allowRegistration")) {
                saveSetting("system.allowRegistration", settings.get("allowRegistration").toString(), "system", "允许注册");
            }
            
            // 如果维护模式改变，发送通知
            if (maintenanceModeChanged) {
                notificationService.sendMaintenanceNotification(newMaintenanceMode);
            }
            
            return Result.success("系统配置更新成功");
        } catch (Exception e) {
            logger.error("更新系统配置失败", e);
            return Result.error("更新系统配置失败");
        }
    }

    /**
     * 获取邮件配置
     */
    @GetMapping("/email")
    public Result<Map<String, Object>> getEmailSettings() {
        try {
            Map<String, Object> settings = new HashMap<>();
            
            // 从数据库获取配置
            settings.put("smtpHost", getSettingValue("email.smtpHost", "smtp.qq.com"));
            settings.put("smtpPort", Integer.parseInt(getSettingValue("email.smtpPort", "587")));
            settings.put("encryption", getSettingValue("email.encryption", "tls"));
            settings.put("fromEmail", getSettingValue("email.fromEmail", ""));
            settings.put("password", getSettingValue("email.password", ""));
            settings.put("fromName", getSettingValue("email.fromName", "资源回收管理平台"));
            settings.put("enabled", Boolean.parseBoolean(getSettingValue("email.enabled", "false")));
            
            return Result.success(settings);
        } catch (Exception e) {
            logger.error("获取邮件配置失败", e);
            return Result.error("获取邮件配置失败");
        }
    }

    /**
     * 更新邮件配置
     */
    @PutMapping("/email")
    public Result<String> updateEmailSettings(@RequestBody Map<String, Object> settings) {
        try {
            // 保存各个配置项到数据库
            if (settings.containsKey("smtpHost")) {
                saveSetting("email.smtpHost", settings.get("smtpHost").toString(), "email", "SMTP服务器");
            }
            if (settings.containsKey("smtpPort")) {
                saveSetting("email.smtpPort", settings.get("smtpPort").toString(), "email", "SMTP端口");
            }
            if (settings.containsKey("encryption")) {
                saveSetting("email.encryption", settings.get("encryption").toString(), "email", "加密方式");
            }
            if (settings.containsKey("fromEmail")) {
                saveSetting("email.fromEmail", settings.get("fromEmail").toString(), "email", "发件邮箱");
            }
            if (settings.containsKey("password")) {
                saveSetting("email.password", settings.get("password").toString(), "email", "邮箱密码");
            }
            if (settings.containsKey("fromName")) {
                saveSetting("email.fromName", settings.get("fromName").toString(), "email", "发件人名称");
            }
            if (settings.containsKey("enabled")) {
                saveSetting("email.enabled", settings.get("enabled").toString(), "email", "启用邮件通知");
            }
            
            return Result.success("邮件配置更新成功");
        } catch (Exception e) {
            logger.error("更新邮件配置失败", e);
            return Result.error("更新邮件配置失败");
        }
    }


    /**
     * 获取库存配置
     */
    @GetMapping("/inventory")
    public Result<Map<String, Object>> getInventorySettings() {
        try {
            Map<String, Object> settings = new HashMap<>();
            settings.put("lowStockThreshold", Integer.parseInt(getSettingValue("inventory.lowStockThreshold", "100")));
            settings.put("fullStockThreshold", Integer.parseInt(getSettingValue("inventory.fullStockThreshold", "2000")));
            settings.put("autoUpdate", Boolean.parseBoolean(getSettingValue("inventory.autoUpdate", "true")));
            settings.put("checkFrequency", getSettingValue("inventory.checkFrequency", "hourly"));
            settings.put("emailAlerts", Boolean.parseBoolean(getSettingValue("inventory.emailAlerts", "true")));
            return Result.success(settings);
        } catch (Exception e) {
            logger.error("获取库存配置失败", e);
            return Result.error("获取库存配置失败");
        }
    }

    /**
     * 更新库存配置
     */
    @PutMapping("/inventory")
    public Result<String> updateInventorySettings(@RequestBody Map<String, Object> settings) {
        try {
            // 保存各个库存配置项到数据库
            if (settings.containsKey("lowStockThreshold")) {
                saveSetting("inventory.lowStockThreshold", settings.get("lowStockThreshold").toString(), "inventory", "低库存阈值");
            }
            if (settings.containsKey("fullStockThreshold")) {
                saveSetting("inventory.fullStockThreshold", settings.get("fullStockThreshold").toString(), "inventory", "库存满载阈值");
            }
            if (settings.containsKey("autoUpdate")) {
                saveSetting("inventory.autoUpdate", settings.get("autoUpdate").toString(), "inventory", "自动库存更新");
            }
            if (settings.containsKey("checkFrequency")) {
                saveSetting("inventory.checkFrequency", settings.get("checkFrequency").toString(), "inventory", "库存检查频率");
            }
            if (settings.containsKey("emailAlerts")) {
                saveSetting("inventory.emailAlerts", settings.get("emailAlerts").toString(), "inventory", "库存预警邮件");
            }
            
            return Result.success("库存配置更新成功");
        } catch (Exception e) {
            logger.error("更新库存配置失败", e);
            return Result.error("更新库存配置失败");
        }
    }

    /**
     * 获取通知配置
     */
    @GetMapping("/notifications")
    public Result<Map<String, Object>> getNotificationSettings() {
        try {
            Map<String, Object> settings = new HashMap<>();
            settings.put("newOrderNotification", Boolean.parseBoolean(getSettingValue("notification.newOrderNotification", "true")));
            settings.put("orderStatusUpdate", Boolean.parseBoolean(getSettingValue("notification.orderStatusUpdate", "true")));
            settings.put("maintenanceNotification", Boolean.parseBoolean(getSettingValue("notification.maintenanceNotification", "true")));
            settings.put("userRegistrationNotification", Boolean.parseBoolean(getSettingValue("notification.userRegistrationNotification", "true")));
            return Result.success(settings);
        } catch (Exception e) {
            logger.error("获取通知配置失败", e);
            return Result.error("获取通知配置失败");
        }
    }

    /**
     * 更新通知配置
     */
    @PutMapping("/notifications")
    public Result<String> updateNotificationSettings(@RequestBody Map<String, Object> settings) {
        try {
            // 保存各个通知配置项到数据库
            if (settings.containsKey("newOrderNotification")) {
                saveSetting("notification.newOrderNotification", settings.get("newOrderNotification").toString(), "notification", "新订单通知");
            }
            if (settings.containsKey("orderStatusUpdate")) {
                saveSetting("notification.orderStatusUpdate", settings.get("orderStatusUpdate").toString(), "notification", "订单状态更新通知");
            }
            if (settings.containsKey("maintenanceNotification")) {
                saveSetting("notification.maintenanceNotification", settings.get("maintenanceNotification").toString(), "notification", "系统维护通知");
            }
            if (settings.containsKey("userRegistrationNotification")) {
                saveSetting("notification.userRegistrationNotification", settings.get("userRegistrationNotification").toString(), "notification", "用户注册通知");
            }
            
            return Result.success("通知配置更新成功");
        } catch (Exception e) {
            logger.error("更新通知配置失败", e);
            return Result.error("更新通知配置失败");
        }
    }

    /**
     * 获取配置值的辅助方法
     * @param key 配置键
     * @param defaultValue 默认值
     * @return 配置值
     */
    private String getSettingValue(String key, String defaultValue) {
        Optional<SystemSettings> setting = settingsRepository.findBySettingKey(key);
        return setting.map(SystemSettings::getSettingValue).orElse(defaultValue);
    }

    /**
     * 保存配置的辅助方法
     * @param key 配置键
     * @param value 配置值
     * @param type 配置类型
     * @param description 配置描述
     */
    private void saveSetting(String key, String value, String type, String description) {
        Optional<SystemSettings> existingSetting = settingsRepository.findBySettingKey(key);
        
        SystemSettings setting;
        if (existingSetting.isPresent()) {
            setting = existingSetting.get();
            setting.setSettingValue(value);
        } else {
            setting = new SystemSettings();
            setting.setSettingKey(key);
            setting.setSettingValue(value);
            setting.setSettingType(type);
            setting.setDescription(description);
        }
        
        settingsRepository.save(setting);
    }
}

